package com.code.gateway.filter;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;

/**
 * Created by IntelliJ IDEA.
 *
 * @author: Yan
 * @date: 2023/03/29
 *
 * 修改微服务响应体数据，解决数据乱码问题
 */
@Component
public class ResponseBodyGlobalFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse httpResponse = exchange.getResponse();
        DataBufferFactory bufferFactory = httpResponse.bufferFactory();

        ServerHttpResponseDecorator responseDecorator = new ServerHttpResponseDecorator(httpResponse){
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                if (body instanceof Flux) {
                    Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
                    return super.writeWith(fluxBody.buffer().map(dataBuffers -> {
                        // DefaultDataBufferFactory join 乱码的问题解决
                        DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
                        DataBuffer join = dataBufferFactory.join(dataBuffers);
                        byte[] content = new byte[join.readableByteCount()];
                        join.read(content);
                        // 释放掉内存
                        DataBufferUtils.release(join);

                        String sb = new String(content, Charset.forName("UTF-8"));

                        if (!isJsonStr(sb)){
                            byte[] uppedContent = sb.getBytes(Charset.forName("UTF-8"));
                            return bufferFactory.wrap(uppedContent);
                        }

                        JSONObject jsonObject = JSONUtil.parseObj(sb);
                        byte[] uppedContent = jsonObject.toString().getBytes(Charset.forName("UTF-8"));
                        return bufferFactory.wrap(uppedContent);
                    }));
                }
                return super.writeWith(body);
            }
        };
        return chain.filter(exchange.mutate().response(responseDecorator).build());
    }

    @Override
    public int getOrder() {
        return -2;
    }

    private boolean isJsonStr(String data) {
        if (JSONUtil.isJson(data) || JSONUtil.isJsonArray(data)) {
            return true;
        }
        return false;
    }

}
